package com.nondo.dean.platform.controller.api.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.nondo.dean.common.annotation.ApiVersion;
import com.nondo.dean.common.tool.BeanUtils;
import com.nondo.dean.common.tool.ValidateUtil;
import com.nondo.dean.common.web.Page;
import com.nondo.dean.common.web.Query;
import com.nondo.dean.common.web.View;
import com.nondo.dean.platform.domain.User;
import com.nondo.dean.platform.model.UserBean;
import com.nondo.dean.platform.model.param.UserParam;
import com.nondo.dean.platform.model.result.OrderUserResult;
import com.nondo.dean.platform.model.result.UserAreaResult;
import com.nondo.dean.platform.service.UserService;

/**
 * 用户管理后台接口
 * @author zlj
 * @date 2018年3月27日
 */
@RestController("apiAdminUser")
@RequestMapping("/{v}/admin/user")
public class UserController {
    
    @Autowired
    UserService userService;
    
    /**
     * 查看用户详情
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/info/{id}")
    public View<User> info(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View<User> view = new View<User>(20000, "获取数据成功");
        
        User user = null;
        if (id != null) {
            user = userService.selectUser(id);
        } else {
            user = new User();
        }

        view.setData(user);
        return view;
    }
    
    /**
     * 添加用户
     * @param request
     * @param response
     * @param user 用户信息 {@link User}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/add")
    public View<User> add(HttpServletRequest request, HttpServletResponse response,
            @Validated @RequestBody User user, BindingResult result) {
        View<User> view = new View<User>(20000, "添加成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            User userDb = this.userService.selectUserByName(user.getUserName());
            if (userDb != null) {
                return View.of500Error("用户名称已存在");
            }
            this.userService.addUser(user);
        }
        return view;
    }

    /**
     * 更新用户
     * @param request
     * @param response
     * @param user 用户信息 {@link User}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/update")
    public View<User> update(HttpServletRequest request,
            HttpServletResponse response,
            @Validated @RequestBody User user, BindingResult result) {
        View<User> view = new View<User>(20000, "更新成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            User userDb = this.userService.selectUserByName(user.getUserName());
            if (userDb.getUserName().equals(user.getUserName()) && userDb.getId() != user.getId()) {
                return View.of500Error("用户名称已存在");
            }
            BeanUtils.copy(user, userDb);
            this.userService.updateUser(userDb);
        }

        return view;
    }

    /**
     * 获取用户分页查询列表
     * @param request
     * @param response
     * @param query
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/list")
    public View<Page<User>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<User> query) {
        View<Page<User>> view = new View<Page<User>>(20000, "获取列表成功");

        User user = query.getData();

        Page<User> page = new Page<User>(query.getPage(), query.getSize(), userService.count(user));
        
        List<User> userList = userService.getUserList(query.getOffset(), query.getLimit(), user);
        
        page.setContent(userList);
        
        view.setData(page);
        
        return view;
    }

    /**
     * 删除用户
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ApiVersion(1)
    @SuppressWarnings("rawtypes")
    @RequestMapping("/delete/{id}")
    public View delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View view = new View(20000, "删除成功");

        User user = userService.selectUser(id);
        user.setDelFlag(String.valueOf(1));
        this.userService.updateUser(user);

        return view;
    }
    
    /**
     * 按照查询条件获取用户列表
     * @param request
     * @param response
     * @param user 
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/search")
    public View<List<UserBean>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody User user) {
        View<List<UserBean>> view = new View<List<UserBean>>(20000, "获取列表成功");

        List<UserBean> userList = userService.getUserList(user);
        if (userList.size() > 100){
            userList = new ArrayList<UserBean>();
            view.setData(userList);
            view.setCode(View.STATE_ERROR_PARAMS);
            view.setMessage("匹配用户数量太多，请调整输入名称");
            return view;
        }
        
        view.setData(userList);
        
        return view;
    }

    /**
     * 修改经销商对应的接单员
     * @param request
     * @param response
     * @param
     * @param result
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/update/order/user")
    public View<Integer> updateClerkOrdering(HttpServletRequest request,
                                            HttpServletResponse response,
                                            @Validated @RequestBody UserParam userParam, BindingResult result) {
        View<Integer> view = new View<Integer>(20000, "更新成功");
        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            int message=userService.updateClerkOrdering(userParam);
            if(message<0){
                return View.of500Error("发生异常,更新失败");
            }
        }
        userService.updateClerkOrdering(userParam);
        return view;
    }

    /**
     * 查询经销商对应的接单员
     * @param request
     * @param response
     * @param query
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/query/dealer/order/user")
    public View<Page<UserAreaResult>> selectPickUpTheDealer(HttpServletRequest request,
                                                            HttpServletResponse response,@RequestBody Query<User> query) {
        View<Page<UserAreaResult>> view = new View<Page<UserAreaResult>>(20000, "查询成功");
        User user = query.getData();
        if(user == null){
            user =new User();
        }
        Page<UserAreaResult> page = new Page<UserAreaResult>(query.getPage(), query.getSize(), userService.count(user));
        List<UserAreaResult> userAreaResults= userService.queryPickUpTheDealer(query.getOffset(),query.getLimit(),user);
        page.setContent(userAreaResults);
        view.setData(page);
        return view;
    }
    
    /**
     * 查询用户基本信息
     * @param request
     * @param response
     * @param id 用户ID
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/query/{id}")
    public View<OrderUserResult> queryUserInfo(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View<OrderUserResult> view = new View<OrderUserResult>(20000, "获取数据成功");
        
        OrderUserResult userResult = new OrderUserResult();
        if (id != null) {
            userResult = userService.getUserResult(id);
        }
        view.setData(userResult);
        
        return view;
    }
    
}